-module(agent_ctr).
-behaviour(gen_server).
-export([start_link/0, stop/0, init/1, terminate/2, code_change/3, handle_cast/2, handle_info/2, handle_call/3 ]).
-include("common.hrl").

-record(state, {id = 0}).
start_link() ->	
	{ok,Idx}=application:get_env(index),
    {ok, MaxAgent} = application:get_env(maxagent),
	db:load_tables(?AgentTabs),
	inets:start(), 
    process_flag(trap_exit, true),
    gen_server:start_link(?MODULE, [Idx,MaxAgent], []).
	
stop() ->
    gen_server:cast(?MODULE, stop).

init([Idx,MaxAgent]) ->
	?debug("agent_ctr registe,MaxAgent=~p", [MaxAgent]),
	server_tools:send_to_agent_mng({agent_ctr_add, self(), MaxAgent}),
	{ok, #state{id=Idx}}.

terminate(_Reason, #state{id=Idx}) ->
	server_tools:send_to_scene_mng({scene_ctr_del, Idx}),
    ok.

code_change(_OldVsn, State, _Extra) ->    
    {ok, State}.

handle_call(_Request, _From, State) -> 
	?log_warning("unknown call, ~p", [_Request]),
    {reply, ok, State}.

handle_info(_Request, State) ->
	?log_warning("unhandled info:~p", [_Request]),
    {noreply, State}.

handle_cast({agent_add,Sid,SceneIdList,LoginData},State) ->	
	?debug("agent_add LoginData=~p",[LoginData]),
	agent_sup:add(Sid,SceneIdList,LoginData),
	{noreply, State};

handle_cast(stop, State) ->
    {stop, normal, State};

handle_cast(_Request, State) ->
	?log_warning("unknown cast, ~p", [_Request]),
    {noreply, State}.


